﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccessLayer;
using BusinessLogicLayer;

namespace PresentationLayer
{
    public partial class ApproveStockAdjustmentVoucher : System.Web.UI.Page
    {
        ApproveStockAdjustmentVoucherControl control;
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            control = new ApproveStockAdjustmentVoucherControl();

            // Fake users
            string username = "Supervisor1";
            //string username = "StoreMgr1";
            user = control.GetUserByUsername(username);

            if (!IsPostBack)
            {
                lblMessage.Text = "";
                GenerateGridView();
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            List<int> voucherList = Session["AdjustmentDetail"] as List<int>;

            // Update ApprovalBy, ApprovalDate and Status to database
            string redirectURL = control.UpdateVouchers(user, voucherList);

            // Redirect to successful page
            Response.Redirect(redirectURL);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            string redirectURL = control.ReturnToStockAdjustmentVoucherList();
            Response.Redirect(redirectURL);
        }

        private void GenerateGridView()
        {
            List<int> voucherId = Session["AdjustmentDetail"] as List<int>;
            if (voucherId != null)
            {
                int voucherID = voucherId[0];
                List<AdjustmentDetail> list = control.DisplayAdjustmentDetail(voucherID);
                lblRequestedBy.Text = list[0].Adjustment.Employee.EmployeeName;
                lblRequestedDate.Text = Convert.ToDateTime(list[0].Adjustment.RequestedDate).ToShortDateString();
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].ItemCode = list[i].Stationery.ItemName;
                }
                gvAdjustDetail.DataSource = list.OrderBy(x => x.ItemCode);
                gvAdjustDetail.DataBind();
            }
            else
            {
                lblMessage.Text = "No stock adjustment voucher is selected";
                gvAdjustDetail.Visible = false;
                btnApprove.Visible = false;
                lblRequestedBy.Visible = false;
                lblRequestedByLabel.Visible = false;
                lblRequestedDate.Visible = false;
                lblRequestedDateLabel.Visible = false;
            }
        }
    }
}